import fs from 'fs-extra';
import path from "path";
import { BaseTask, TaskResult } from "../../common/tasks/BastTask.js";
import { toolchain } from '../../toolchain.js';
import { WebGLEnv } from '../WebGLEnv.js';

/**生成小游戏预加载清单 */
export class WebGLMiniGamePreloadTask extends BaseTask<void> {
    async run(): Promise<TaskResult<void>> {
        const cdnURL = toolchain.unity.getCDNURL();
        const resVer = await toolchain.unity.getResVersion();
        const list: string[] = [`${cdnURL}/assetbundleconfiglist_${resVer}.ab`];

        if (toolchain.params.channelCfg.preload) {
            const hash = await toolchain.unity.getABFileMD5s();
            for (const p of toolchain.params.channelCfg.preload) {
                const arr = p.split(/\s*\?\?\s*/);
                for (const f of arr) {
                    const lcf = f.toLowerCase();
                    const md5 = hash[`${lcf}.ab`];
                    if (md5) {
                        list.push(`${cdnURL}/${lcf}_${md5}.ab`);
                        break;
                    }    
                }
            }            
        }
        console.log('preload list: \n' + list.join('\n'));
        const assetsDir = toolchain.unity.getAssetsDir();
        await fs.writeFile(path.join(toolchain.params.uploadPath, assetsDir, 'preload.txt'), list.join('\n'), 'utf-8');

        // 修改game.js
        let gameJsModified = false;
        const root = path.join(toolchain.params.workSpacePath, WebGLEnv.ExportMiniGameRoot, WebGLEnv.MiniGameRoot);
        const gameJS = path.join(root, 'game.js');
        const gameJSContent = await fs.readFile(gameJS, 'utf-8');
        const lines = gameJSContent.split(/\r?\n/);
        for (let i = 0, len = lines.length; i < len; i++) {
            if (lines[i].includes('gameManager.startGame()')) {
                const codes = `        wx.request({
            url: \`${toolchain.params.channelCfg.url}/assets/wx/preload.txt?t=${Math.random()}\`,
            success(res) {
                console.log('preload list success:', res);
                if (res.statusCode === 200) {
                    GameGlobal.manager.setPreloadList(res.data.split(/\\r?\\n+/));
                }
            },
            complete() {
                console.log('preload complete, start game');
                // 成功与否都开始启动unity
                GameGlobal.manager.startGame();
            }
        });`;
                lines.splice(i, 1, ...codes.split(/\r?\n/));
                await fs.writeFile(gameJS, lines.join('\n'), 'utf-8');
                gameJsModified = true;
                break;
            }
        }
        
        if (!gameJsModified) {
            return { success: false, errorCode: 1, message: 'game.js修改失败，无法使用微信预加载', data: void 0 };
        }

        return { success: true, errorCode: 0, data: void 0 };
    }
}
